import { Box3Get, escapeHtml, get } from "@ap/util/request";
import * as vscode from "vscode";
import {
  showErrorMessage,
  showInformationMessage,
} from "@ap/util/vscode/message";
import { auth } from "@ap/util/request";
import { updatePackageJson, getPackageJson } from "@ap/util/packageJson";
import { arenaErrorMsg } from "@ap/util/vscode/errorMsg";
import { CommandId, photoMap } from "@ap/command";
import { PackageConfig } from "@ap/types/config";
import insertCode from "@ap/util/vscode/insertCode";
import openInternetImage from "@ap/webView/img";
import { getGroupProject, STATIC_URL } from "./getGroupProject";
import { convertTimestampToDateString } from "./getMapStorage";
import { extractAudioFileName } from "./getMapAudioList";
import { transformDao3Resources } from "./transformDao3Resources";
/**
 * 物品接口，扩展了共享的物品属性，添加了描述和ID。
 */
interface Item {
  name: string;
  size: number;
  previewImage: string;
}

export interface ExtendedQuickPickItem extends vscode.QuickPickItem {
  view: string;
}

/**
 * 异步获取扩展地图列表数组。
 * @returns 返回承诺，解析为数据项数组。
 */
export async function getBox3MapPhotoList(): Promise<
  ExtendedQuickPickItem[] | undefined
> {
  return getPackageJson<PackageConfig>("map").then(async (packageJson) => {
    if (packageJson) {
      const mapId = packageJson.id;
      if (mapId) {
        const response = await getGroupProject(mapId);
        if (!response) {
          return;
        }

        const requestOptions2 = {
          url: STATIC_URL + response.data.pictureAssets,
        };
        const response2 = await get<Record<string, any>>(
          requestOptions2,
          "地图图片",
        );
        if (!response2) {
          showErrorMessage(`获取地图图片数据失败`);
          return;
        }
        /**+
         * 处理响应数据，映射物品到数据项格式，并转义HTML字符以防止XSS攻击。
         */
        let dataSource: ExtendedQuickPickItem[] = [];
        Object.entries(response2).forEach(([key, value]) => {
          dataSource.push({
            label: extractAudioFileName(key),
            description:
              value.size >= 1000000
                ? (value.size / 1000000).toFixed(2).toString() + "MB"
                : (value.size / 1000).toFixed(2).toString() + "KB",
            detail: convertTimestampToDateString(value.updateAt),
            view: "https://assets.box3.fun/engine/m/" + value.previewImage,
          });
        });
        photoMap.description = `共${dataSource.length}项`;
        return dataSource;
      }
    }
  });
}
